import React, { useState, useEffect } from 'react';
import {
    Card,
    Form,
    Input,
    Switch,
    Button,
    message,
    Select,
    Space,
    Spin
} from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import styles from './index.module.css';
import {algorithmApi} from "../../../services/api/algorithm";
import { ALGORITHM_OPTIONS } from '../../../constans/algorithm';

const { TextArea } = Input;
const { Option } = Select;

const AlgorithmEditPage: React.FC = () => {
    const [form] = Form.useForm();
    const navigate = useNavigate();
    const { algorithmId } = useParams<{ algorithmId: string }>();
    const [loading, setLoading] = useState(false);
    const [initialLoading, setInitialLoading] = useState(true);

    // 获取算法配置详情
    const fetchAlgorithmDetail = async () => {
        try {
            if (!algorithmId) return;
            const response = await algorithmApi.getAlgorithmDetail(Number(algorithmId));

            if (response.code === 200 && response.data) {
                // 设置表单初始值
                form.setFieldsValue({
                    ...response.data,
                    additionalParams: response.data.additionalParams ?
                        JSON.stringify(response.data.additionalParams, null, 2) : undefined
                });
            } else {
                message.error(response.message || '获取配置详情失败');
            }
        } catch (error) {
            console.error('获取算法配置详情失败:', error);
            message.error('获取配置详情失败，请重试');
        } finally {
            setInitialLoading(false);
        }
    };

    // 提交表单
    const handleSubmit = async (values: any) => {
        try {
            setLoading(true);

            // 处理额外参数
            let additionalParams = undefined;
            if (values.additionalParams) {
                try {
                    additionalParams = JSON.parse(values.additionalParams);
                } catch (e) {
                    message.error('额外参数格式不正确');
                    return;
                }
            }

            const submitData = {
                ...values,
                algorithmId: Number(algorithmId),
                additionalParams
            };

            const response = await algorithmApi.updateAlgorithm(submitData);

            if (response.code === 200 && response.data) {
                message.success('更新配置成功');
                navigate('/algorithm/list');
            } else {
                message.error(response.message || '更新失败');
            }
        } catch (error) {
            console.error('更新算法配置失败:', error);
            message.error('更新失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchAlgorithmDetail();
    }, [algorithmId]);

    if (initialLoading) {
        return (
            <div className={styles.loadingContainer}>
                <Spin size="large" />
            </div>
        );
    }

    return (
        <div className={styles.container}>
            <Card title="修改算法配置" bordered={false}>
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleSubmit}
                >
                    <Form.Item
                        label="算法名称"
                        name="algorithmName"
                        rules={[{ required: true, message: '请选择算法名称' }]}
                    >
                        <Select placeholder="请选择算法名称">
                            {ALGORITHM_OPTIONS.map(algorithm => (
                                <Option key={algorithm.code} value={algorithm.code}>
                                    {algorithm.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label="配置名称"
                        name="name"
                        rules={[{ required: true, message: '请输入配置名称' }]}
                    >
                        <Input placeholder="请输入配置名称" maxLength={50} />
                    </Form.Item>

                    <Form.Item
                        label="算法描述"
                        name="description"
                    >
                        <TextArea
                            placeholder="请输入算法描述"
                            rows={4}
                            maxLength={200}
                            showCount
                        />
                    </Form.Item>

                    <Form.Item
                        label="区分大小写"
                        name="caseSensitive"
                        valuePropName="checked"
                    >
                        <Switch />
                    </Form.Item>

                    <Form.Item
                        label="忽略空白字符"
                        name="ignoreWhitespace"
                        valuePropName="checked"
                    >
                        <Switch />
                    </Form.Item>

                    <Form.Item
                        label="文本标准化"
                        name="normalizeText"
                        valuePropName="checked"
                    >
                        <Switch />
                    </Form.Item>

                    <Form.Item
                        label="是否启用"
                        name="isActive"
                        rules={[{ required: true, message: '请选择是否启用' }]}
                    >
                        <Select>
                            <Option value={1}>启用</Option>
                            <Option value={0}>停用</Option>
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label="额外参数"
                        name="additionalParams"
                        tooltip="请输入有效的 JSON 格式"
                    >
                        <TextArea
                            placeholder="请输入额外参数（JSON格式）"
                            rows={4}
                            onChange={(e) => {
                                try {
                                    if (e.target.value) {
                                        JSON.parse(e.target.value);
                                        form.setFields([{ name: 'additionalParams', errors: [] }]);
                                    }
                                } catch (error) {
                                    form.setFields([
                                        {
                                            name: 'additionalParams',
                                            errors: ['请输入有效的 JSON 格式']
                                        }
                                    ]);
                                }
                            }}
                        />
                    </Form.Item>

                    <Form.Item>
                        <Space size="middle">
                            <Button type="primary" htmlType="submit" loading={loading}>
                                提交
                            </Button>
                            <Button onClick={() => navigate('/algorithm/list')}>
                                取消
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    );
};

export default AlgorithmEditPage;
